<template>
  <div>
    <!-- 功能按钮 -->
    <el-form class="tableSearch" size="mini">
      <el-form-item>
        <el-button type="primary" size="mini" @click="$router.back(-1)">返回</el-button>
        <el-button type="primary" size="mini" @click="submitForm('formdata')">保存</el-button>
        <el-button type="primary" size="mini" @click="openGoodsdialog()">批量添加商品</el-button>
        <el-button type="primary" size="mini" @click="selectTable.handleMultipleDel()">批量删除商品</el-button>
      </el-form-item>
    </el-form>

    <!-- form表单 -->
    <el-form :model="formdata" :rules="rules" ref="formdata" label-width="120px" size="mini">
      <el-row>
        <el-col :span="8">
          <el-form-item label="收货日期：" prop="receiveDate">
            <el-date-picker v-model="formdata.receiveDate" format="yyyy年 MM 月 dd 日" value-format="yyyy-MM-dd" type="date" placeholder="选择收货日期"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="订单状态：">
            <el-input v-model="orderStatusArr[formdata.statusFlow]" disabled></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="单据日期：">
            <el-date-picker v-model="formdata.orderDate" format="yyyy年 MM 月 dd 日" value-format="yyyy-MM-dd" type="date" disabled></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="单据编号：">
            <el-input v-model="formdata.purchaseinCode" disabled placeholder="单据状态自动生成"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 表格 -->
    <el-table :data="selectTable.tableData" @selection-change="selectTable.handleMultipleSelect">
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column type="index" label="#" width="55"></el-table-column>
      <el-table-column prop="goodsCode" label="商品货号" align="center"></el-table-column>
      <el-table-column prop="barCode" label="商品条码" align="center"></el-table-column>
      <el-table-column prop="goodsName" label="商品" align="center" width="200"></el-table-column>
      <el-table-column prop="unitName" label="单位" align="center"></el-table-column>
      <el-table-column prop="goodsSpec" label="规格型号" align="center">
        <template slot-scope="scope">
          <div v-for="(item, index) in scope.row.goodsSpec" :key="index">
            <span>{{item.paramName}} :</span>
            <span>{{item.paramValue}}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="goodsPrice" label="单价" align="center"></el-table-column>
      <el-table-column prop="goodsNum" label="数量" align="center" width="150">
        <template slot-scope="scope">
          <input class="commonInput" v-model="scope.row.goodsNum" size="mini" type="text" style="width:100px" value="1" min="0" maxlength="8" oninput="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'')}else{this.value=this.value.replace(/\D/g,'')}" onafterpaste="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'0')}else{this.value=this.value.replace(/\D/g,'')}">
        </template>
      </el-table-column>
      <el-table-column prop="goodsAmount" label="总价" align="center">
        <template slot-scope="scope">
          <span>{{(scope.row.goodsPrice * scope.row.goodsNum).toFixed(2)}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="180">
        <template slot-scope="scope">
          <el-button type="text" @click="selectTable.handleSingleDel(scope.$index)" size="mini">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 费用表单 -->
    <el-form :model="formdata" label-width="120px" size="mini" style="margin-top:25px;">
      <el-row>
        <el-col :span="8">&nbsp;</el-col>
        <el-col :span="8">
          <el-form-item label="操作员：">
            <el-input v-model="formdata.creator" disabled></el-input>
          </el-form-item>
          <el-form-item label="备注：">
            <el-input v-model="formdata.remark" type="textarea" maxlength="50"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="总计：">
            <el-input v-model="formdataTotal" disabled></el-input>
          </el-form-item>
          <el-form-item label="运费：">
            <sd-input :val.sync="formdata.freight"></sd-input>
          </el-form-item>
          <el-form-item label="应付总计：">
            <el-input v-model="formdataAllTotal" disabled></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 商品选择弹出框 -->
    <el-dialog title="商品选择" :visible.sync="goodsTable.dialog" :closeOnClickModal="false" :closeOnPressEscape="false">
      <el-form label-width="0" size="mini">
        <el-form-item>
          <el-button type="primary" @click="handleSelectGoods()">选择</el-button>
          <el-button @click="goodsTable.dialog=false">取消</el-button>
        </el-form-item>
      </el-form>
      <el-table :data="goodsTable.tableData" tooltip-effect="dark" @selection-change="goodsTable.handleMultipleSelect" :row-key="goodsTable.getRowKeys">
        <el-table-column type="selection" width="55" :reserve-selection="true"></el-table-column>
        <el-table-column prop="goodsName" label="商品" align="center"></el-table-column>
        <el-table-column prop="unitName" label="单位" align="center"></el-table-column>
        <el-table-column prop="goodsCode" label="商品货号" align="center"></el-table-column>
        <el-table-column prop="barCode" label="商品条码" align="center"></el-table-column>
        <el-table-column prop="parameter" label="规格型号" align="center">
          <template slot-scope="scope">
            <div v-for="(item,index) in scope.row.goodsSpec" :key="index">
              <span v-if="item!=null">{{item.paramName}} :</span>
              <span v-if="item!=null">{{item.paramValue}}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="isFreight" label="含运费" align="center">
          <template slot-scope="scope">
            <span v-show="scope.row.isFreight=='1'">含运费</span>
            <span v-show="scope.row.isFreight=='0'">不含运费</span>
          </template>
        </el-table-column>
        <el-table-column prop="freight" label="运费" align="center"></el-table-column>
        <el-table-column prop="goodsPrice" label="价格" align="center"></el-table-column>
      </el-table>
      <page-unit :pageData="goodsTable.pageData" :func="_getPurchaseGoodsPage"></page-unit>
    </el-dialog>

  </div>
</template>
<script>
import { mapState } from "vuex";
import u from "@/util";
import s from "@/util/state"
import { TableHandle } from "@/util/class";
import sdInput from "@/components/SdInput";
import pageUnit from "@/components/Page";
import {
  saveGoodsPurchase,
  selectBaseShopPageList,
  getPurchaseGoodsPage
} from "@/api";
export default {
  components: { sdInput, pageUnit },
  data () {
    return {
      selectdata: {
        keywordGoods: "",  // 商品搜索关键词
      },
      orderStatusArr: s.orderStatusArr, // 单据状态
      formdata: {
        receiveDate: "",  // 收货日期
        statusFlow: "0",  // 订单状态
        orderDate: "",  // 单据日期
        purchaseinCode: "",  // 单据编号
        creator: "",  // 操作员
        remark: "",  // 备注
        purchaseAmount: 0,  // 总计
        freight: 0,  // 运费
        amount: 0  // 应付总计
      },
      rules: {
        receiveDate: [{ required: true, message: "请选择收货时间", trigger: "blur" }]
      },
      goodsTable: new TableHandle(),  // 商品数组对象
      selectTable: new TableHandle(),  // 选择都商品数组对象
    };
  },
  computed: {
    ...mapState({
      companyName: state => state.companyName,
      merchantId: state => state.merchantId,
      linkName: state => state.linkName,
      mobile: state => state.mobile,
      userId: state => state.userId,
    }),
    formdataTotal: function () {
      let priceItem = 0,
        freightItem = 0
      this.selectTable.tableData.forEach(i => {
        i.goodsAmount = Number(i.goodsPrice) * Number(i.goodsNum)
        priceItem += i.goodsAmount
        if(Number(i.isFreight) === 0) {
          freightItem +=  Number(i.freight) * Number(i.goodsNum)
        }
      })
      this.formdata.purchaseAmount = isNaN(priceItem) ? 0 : priceItem.toFixed(2)
      this.formdata.freight = isNaN(freightItem) ? 0 : freightItem.toFixed(2)
      return this.formdata.purchaseAmount
    },
    formdataAllTotal: function () {
      return (Number(this.formdata.purchaseAmount) + Number(this.formdata.freight)).toFixed(2)
    },
  },
  mounted () {
    this.init();  // 初始化操作员
    this.data();  // 初始化单据日期
  },
  methods: {
    init () {
      if (this.linkName != undefined && this.linkName != "") {
        this.formdata.creator = this.linkName;
      } else {
        this.formdata.creator = this.mobile;
      }
    },

    submitForm (formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.handleSave();
        } else {
          return false;
        }
      });
    },

    // 初始化单据日期
    data (picker) {
      new Date(2000, 10, 10, 10, 10), new Date(2000, 10, 11, 10, 10);
      const date = new Date();
      var datas = date.setTime(date.getTime());
      var datase = u.foryear(parseInt(datas));
      this.formdata.orderDate = datase;
    },

    // 点击批量添加商品
    openGoodsdialog () {
      this.goodsTable.dialog = true
      this._getPurchaseGoodsPage(this.goodsTable.pageData.pageSize, 1)
    },

    // 获取商品列表
    _getPurchaseGoodsPage (pageSize, pageNo) {
      getPurchaseGoodsPage({
        shopId: this.merchantId,
        goodsName: this.selectdata.keywordGoods,
        pageSize: pageSize,
        pageNum: pageNo,
        status: 0
      }).then(res => {
        res.data.list.forEach(i => i.goodsNum = 0)
        this.goodsTable.tableData = res.data.list
        this.goodsTable.pageData.totalItems = res.data.pageTotal
      });
    },
    
    // 保存，新增报货订单
    handleSave () {
      // 判断数组不能为空
      if (this.selectTable.tableData.length == 0) {
        this.$message.error("请刷新页面，选择商品")
        return false
      }

      // 判断数量不能小于最小起订数量
      if(this.selectTable.tableData.some(i => i.goodsNum < i.minNum)) {
        this.$message.error("数量不能小于最小起订数量")
        return false
      }

      this.selectTable.tableData.forEach(i => {
        i.goodsOrganizationSkuId = i.id
        delete i.createTime
        delete i.updateTime
      });

      saveGoodsPurchase({
        shopId: this.merchantId,
        creator: this.userId,
        receiveDate: this.formdata.receiveDate,
        orderDate: this.formdata.orderDate,
        statusFlow: this.formdata.statusFlow,
        purchaseinCode: this.formdata.purchaseinCode,
        remark: this.formdata.remark,
        purchaseAmount: this.formdata.purchaseAmount,
        freight: this.formdata.freight,
        taxAmount: this.formdata.taxAmount,
        amount: this.formdataAllTotal,
        goodsList: JSON.stringify(this.selectTable.tableData),
        consignee: '',
        shopName: this.companyName,
        linkman: this.linkName,
        address: '',
        purchaseType: 0
      }).then(res => {
        if (res.code == 200) {
          this.$message.success(res.msg)
          u.routerTo("/order-center/purchase-management/purchase-storeReceiptMg");
        } 
      });
    },

    // 点击选择商品
    handleSelectGoods () {
      if (this.goodsTable.isSelect(2, this, '请先选择商品！')) {
        this.goodsTable.multipleSelectTable.forEach(i => {
          i.purchasePriceshow = i.purchasePrice
        })
        this.selectTable.tableData = this.goodsTable.handleMultipleConfirm(this.selectTable.tableData, 'goodsId')
        this.goodsTable.dialog = false
      }
    },
  }
};
</script>

<style lang="less">
.el-input-group__append {
    background-color: #409eff;
    border-color: #409eff;
    color: #ffffff;
}

.el-dialog__header {
  background-color: #25a0e9;
  .el-dialog__title {
    color: #FFFFFF;
  }
  .el-dialog__close {
    color: #FFFFFF;
    &:hover{
      &:before {
        color: #FFFFFF;
      }
    }
  }
}
</style>
